<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="sku_id" prop="skcId">
        <el-input
          v-model="queryParams.skcId"
          placeholder="请输入sku_id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="productCreatedAt">
        <el-date-picker clearable
                        v-model="queryParams.productCreatedAt"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="productUpdatedAt">
        <el-date-picker clearable
                        v-model="queryParams.productUpdatedAt"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="名称" prop="spuName">
        <el-input
          v-model="queryParams.spuName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商家id" prop="supplierId">
        <el-input
          v-model="queryParams.supplierId"
          placeholder="请输入商家id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生命周期状态" prop="selectStatus">
        <el-select v-model="queryParams.selectStatus" placeholder="请选择生命周期状态" clearable>
          <el-option
            v-for="dict in dict.type.temu_select_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['temu:spu:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['temu:spu:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['temu:spu:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['temu:spu:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-sort-down"
          size="mini"
          @click="handleSyncSpuFromTemu"
          v-hasPermi="['temu:spu:sync']"
        >从temu同步</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="SPU_ID" align="center" prop="spuId" />
      <el-table-column label="sku_id" align="center" prop="skcId" />
      <el-table-column label="创建时间" align="center" prop="productCreatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productCreatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="productUpdatedAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productUpdatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="spuName" />
      <el-table-column label="图片列表" align="center" prop="carouselImageUrlList" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.carouselImageUrlList" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商家id" align="center" prop="supplierId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.temu_supplier_id" :value="scope.row.supplierId"/>
        </template>
      </el-table-column>
      <el-table-column label="购买地址" align="center" prop="buyUrl" >
        <template slot-scope="scope">
          <a :href="scope.row.buyUrl" target="_blank" class="buttonText">点击跳转</a>
        </template>
      </el-table-column>
      <el-table-column label="生命周期状态" align="center" prop="selectStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.temu_select_status" :value="scope.row.selectStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['temu:spu:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['temu:spu:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改spu对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="sku_id" prop="skcId">
          <el-input v-model="form.skcId" placeholder="请输入sku_id" />
        </el-form-item>
        <el-form-item label="创建时间" prop="productCreatedAt">
          <el-date-picker clearable
                          v-model="form.productCreatedAt"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="productUpdatedAt">
          <el-date-picker clearable
                          v-model="form.productUpdatedAt"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="名称" prop="spuName">
          <el-input v-model="form.spuName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图片列表" prop="carouselImageUrlList">
          <el-input v-model="form.carouselImageUrlList" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商家id" prop="supplierId">
          <el-input v-model="form.supplierId" placeholder="请输入商家id" />
        </el-form-item>
        <el-form-item label="购买地址" prop="buyUrl">
          <el-input v-model="form.buyUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="生命周期状态" prop="selectStatus">
          <el-select v-model="form.selectStatus" placeholder="请选择生命周期状态">
            <el-option
              v-for="dict in dict.type.temu_select_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">sku信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddTemuSku">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteTemuSku">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="temuSkuList" :row-class-name="rowTemuSkuIndex" @selection-change="handleTemuSkuSelectionChange" ref="temuSku">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="商家" prop="supplierId" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.supplierId" placeholder="请选择商家">
                <el-option
                  v-for="dict in dict.type.temu_supplier_id"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="skc_id" prop="skcId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.skcId" placeholder="请输入skc_id" />
            </template>
          </el-table-column>
          <el-table-column label="商家价格" prop="supplierPrice" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.supplierPrice" placeholder="请输入商家价格" />
            </template>
          </el-table-column>
          <el-table-column label="货号" prop="extCode" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.extCode" placeholder="请输入货号" />
            </template>
          </el-table-column>
          <el-table-column label="宽(mm)" prop="width" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.width" placeholder="请输入宽(mm)" />
            </template>
          </el-table-column>
          <el-table-column label="高(mm)" prop="height" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.height" placeholder="请输入高(mm)" />
            </template>
          </el-table-column>
          <el-table-column label="重量(mg)" prop="weight" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.weight" placeholder="请输入重量(mg)" />
            </template>
          </el-table-column>
          <el-table-column label="库存类型" prop="stockType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.stockType" placeholder="请选择库存类型">
                <el-option
                  v-for="dict in dict.type.temu_stock_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="库存数量" prop="stockQuantity" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.stockQuantity" placeholder="请输入库存数量" />
            </template>
          </el-table-column>
          <el-table-column label="冻结库存数量" prop="frozenStockQuantity" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.frozenStockQuantity" placeholder="请输入冻结库存数量" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSpu, getSpu, delSpu, addSpu, updateSpu,syncFromTemu } from "@/api/temu/spu";

export default {
  name: "Spu",
  dicts: ['temu_select_status', 'temu_stock_type', 'temu_supplier_id'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTemuSku: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // spu表格数据
      spuList: [],
      // sku表格数据
      temuSkuList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        skcId: null,
        productCreatedAt: null,
        productUpdatedAt: null,
        spuName: null,
        carouselImageUrlList: null,
        supplierId: null,
        buyUrl: null,
        selectStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询spu列表 */
    getList() {
      this.loading = true;
      listSpu(this.queryParams).then(response => {
        this.spuList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        spuId: null,
        skcId: null,
        productCreatedAt: null,
        productUpdatedAt: null,
        spuName: null,
        carouselImageUrlList: null,
        supplierId: null,
        buyUrl: null,
        selectStatus: null
      };
      this.temuSkuList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.spuId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加spu";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const spuId = row.spuId || this.ids
      getSpu(spuId).then(response => {
        this.form = response.data;
        this.temuSkuList = response.data.temuSkuList;
        this.open = true;
        this.title = "修改spu";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.temuSkuList = this.temuSkuList;
          if (this.form.spuId != null) {
            updateSpu(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSpu(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const spuIds = row.spuId || this.ids;
      this.$modal.confirm('是否确认删除spu编号为"' + spuIds + '"的数据项？').then(function() {
        return delSpu(spuIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** sku序号 */
    rowTemuSkuIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** sku添加按钮操作 */
    handleAddTemuSku() {
      let obj = {};
      obj.supplierId = "";
      obj.skcId = "";
      obj.productPropertyList = "";
      obj.supplierPrice = "";
      obj.extCode = "";
      obj.len = "";
      obj.width = "";
      obj.height = "";
      obj.weight = "";
      obj.skuPreviewImage = "";
      obj.buyUrl = "";
      obj.stockType = "";
      obj.stockQuantity = "";
      obj.frozenStockQuantity = "";
      this.temuSkuList.push(obj);
    },
    /** sku删除按钮操作 */
    handleDeleteTemuSku() {
      if (this.checkedTemuSku.length == 0) {
        this.$modal.msgError("请先选择要删除的sku数据");
      } else {
        const temuSkuList = this.temuSkuList;
        const checkedTemuSku = this.checkedTemuSku;
        this.temuSkuList = temuSkuList.filter(function(item) {
          return checkedTemuSku.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTemuSkuSelectionChange(selection) {
      this.checkedTemuSku = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('temu/spu/export', {
        ...this.queryParams
      }, `spu_${new Date().getTime()}.xlsx`)
    },

    /** 从temu同步spu数据 */
    handleSyncSpuFromTemu() {
      // 需要将按钮置灰，变成不可点击
      syncFromTemu().then(() => {
        this.getList();
        this.$modal.msgSuccess("成功从temu更新");
      }).catch(() => {});
    }
  }
};
</script>
